package com.cfets.annualAssessment.backgroundController;

import com.cfets.annualAssessment.entity.*;
import com.cfets.annualAssessment.service.QuestionService;
import com.cfets.annualAssessment.util.ExcelUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * Created by ShenYiChou on 2017/1/19.
 */
@Controller
@RequestMapping("/admin/question")
public class QuestionController {
    @Autowired
    private QuestionService questionService;

    @RequestMapping("/index")
    public String index(Model model){
        return "question";
    }

    @GetMapping
    public ResponseEntity<?> questionList(Question question){
        List<Question> questionList = questionService.getAllQuestionPage(question);
        TableContainer tableContainer = new TableContainer();
        tableContainer.setAaData(questionList);
        tableContainer.setiTotalDisplayRecords(question.getTotalCount());
        tableContainer.setiTotalRecords(question.getTotalCount());
        return new ResponseEntity<>(tableContainer, HttpStatus.OK);
    }
    @RequestMapping(value = "/questionConf",method = RequestMethod.GET)
    public ResponseEntity<?> getNewQuestionConf(){
        QuestionConf questionConf = questionService.getQuestionConf();
        return new ResponseEntity<>(questionConf, HttpStatus.OK);
    }
    //得到题库
    @RequestMapping(value = "/restful",method = RequestMethod.POST)
    public ResponseEntity<?> getNewQuestions(AnnualInform annualInform){
        List<Question> questionList = null;
        if(annualInform.getCa_num() == null) {
            return new ResponseEntity<>(false, HttpStatus.OK);
        }
        if(questionService.getQuestionState(annualInform.getCa_num()).isEmpty()) {
            questionList = questionService.newQuestions();
            for (Question item : questionList) {
                item.setAnswer("");
                QuestionState questionState = new QuestionState();
                questionState.setCa_num(annualInform.getCa_num());
                questionState.setQues_id(item.getId());
                questionService.newQuestionState(questionState);
            }
        }else{
            questionList = questionService.getQuestionNowState(annualInform.getCa_num());
            for (Question item : questionList) {
                item.setAnswer("");
            }
        }
        QuestionNowRest questionNowRest = new QuestionNowRest();
        questionNowRest.setQuestionNowList(questionList);
        return new ResponseEntity<>(questionNowRest, HttpStatus.OK);
    }
    //正确答案//没写完
    @RequestMapping(value = "/restful/score",method = RequestMethod.POST)
    public ResponseEntity<?> getScore(AnnualInform annualInform){
        if(annualInform.getCa_num() == null) {
            return new ResponseEntity<>(false, HttpStatus.OK);
        }
        CommPara commPara = questionService.getScore(annualInform.getCa_num());
        //state 清空 根据ca_num
        questionService.delQuestionNowState(annualInform.getCa_num());
        questionService.delQuestionTimeState(annualInform.getCa_num());
        return new ResponseEntity<>(commPara, HttpStatus.OK);
    }
    @RequestMapping(value = "/restful/next",method = RequestMethod.POST)
    public ResponseEntity<?> nextQues(QuestionState questionState){
        if(questionState.getCa_num() == null) {
            return new ResponseEntity<>(false, HttpStatus.OK);
        }
        boolean flag = questionService.updateQuestionState(questionState);

        return new ResponseEntity<>(flag, HttpStatus.OK);
    }
    @RequestMapping(value = "/restful/close",method = RequestMethod.POST)
    public ResponseEntity<?> closeQues(QuesTimeState quesTimeState){
        if(quesTimeState.getCa_num() == null) {
            return new ResponseEntity<>(false, HttpStatus.OK);
        }
        boolean flag = questionService.updateQuestionTime(quesTimeState);
        return new ResponseEntity<>(flag, HttpStatus.OK);
    }
    @RequestMapping(value = "/restful/init",method = RequestMethod.POST)
    public ResponseEntity<?> initQues(AnnualInform annualInform){
        if(annualInform.getCa_num() == null) {
            return new ResponseEntity<>(false, HttpStatus.OK);
        }
        CommPara commPara = this.questionService.getQuesTime(annualInform.getCa_num());
        return new ResponseEntity<>(commPara, HttpStatus.OK);
    }
    @PostMapping
    public ResponseEntity<?> createOrUpdateQuestionConf(@Valid QuestionConf questionConf, BindingResult result) {
        if (result.hasErrors()) {
            return new ResponseEntity<>(result.getAllErrors(), HttpStatus.OK);
        }
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date=new Date();
        String str=sdf.format(date);
        questionConf.setPost_time(str);
        boolean flag = false;
        if(questionService.QuestionsOrNot(questionConf.getQuestion_num())==-2){
            return new ResponseEntity<>(-2, HttpStatus.OK);
        }
        if(questionConf.getId()!=null && questionConf.getId()!=0){
            flag = this.questionService.updateQuestionConf(questionConf);
        }else {
            flag = this.questionService.newQuestionConf(questionConf);
        }
        return new ResponseEntity<>(flag, HttpStatus.OK);
    }

    @RequestMapping(value = "/import")
    public ResponseEntity<?> importExcel(MultipartFile questionFile) {
        try {
            Workbook xwb = WorkbookFactory.create(questionFile.getInputStream());
            Sheet sheet = xwb.getSheetAt(0);
            Row row;
            this.questionService.delAllQuestion();
            for (int i = sheet.getFirstRowNum(); i < sheet.getPhysicalNumberOfRows(); i++) {
                if (i == 0) {
                    continue;
                }
                row = sheet.getRow(i);
                Question question = new Question();
                if(Objects.equals(row.getCell(1).toString(), "")){
                    return new ResponseEntity<>(-1, HttpStatus.OK);//题目为空
                }
                question.setQuestion(row.getCell(1).toString());

                if(!row.getCell(2).toString().matches("[A-Z]")){
                    return new ResponseEntity<>(-2, HttpStatus.OK);//答案格式不对
                }
                question.setAnswer(row.getCell(2).toString());

                question.setA_option(row.getCell(3)!=null?row.getCell(3).toString():"");
                question.setB_option(row.getCell(4)!=null?row.getCell(4).toString():"");
                question.setC_option(row.getCell(5)!=null?row.getCell(5).toString():"");
                question.setD_option(row.getCell(6)!=null?row.getCell(6).toString():"");
                question.setE_option(row.getCell(7)!=null?row.getCell(7).toString():"");
                question.setF_option(row.getCell(8)!=null?row.getCell(8).toString():"");
                question.setG_option(row.getCell(9)!=null?row.getCell(9).toString():"");
                question.setH_option(row.getCell(10)!=null?row.getCell(10).toString():"");
                boolean flag = this.questionService.insertQuestion(question);
                if(!flag){
                    return new ResponseEntity<>(false, HttpStatus.OK);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(false, HttpStatus.OK);
        }
        return new ResponseEntity<>(true, HttpStatus.OK);
    }
    @RequestMapping("/exportEmail")
    public String exportEmail(HttpServletResponse response){
        List<Question> questionList = this.questionService.getAllQuestion();
        ExcelUtil.exportExcel("题库", new String[]{"NO.","题目","正确答案","A","B","C","D","E","F","G","H"},
                new String[]{"","question","answer","A_option","B_option","C_option","D_option","E_option","F_option","G_option","H_option"}, questionList, response );
        return null;
    }
}
